package taskManager.dataAccessLayer;

import java.util.*;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.Query;

import taskManager.commonLayer.Task;

public class TaskDataAccessClass extends EntityBase
{
	private final String entityName = "Tasks";
	
	public Key Insert(Task task)
	{
		Entity taskEntity = new Entity(entityName);
		taskEntity.setProperty("UserID", task.getUserID());
		taskEntity.setProperty("Content", task.getContent());
		taskEntity.setProperty("Completed", task.isCompleted());
		taskEntity.setProperty("Deleted", false);
		return super.Insert(taskEntity);
	}
	
	public void Update(Task task)
	{
		Entity taskEntity = new Entity(task.getTaskKey());
		taskEntity.setProperty("UserKey", task.getUserID());
		taskEntity.setProperty("Content", task.getContent());
		taskEntity.setProperty("Completed", task.isCompleted());
		taskEntity.setProperty("Deleted", task.isDeleted());
		super.Update(taskEntity);
	}
	
	public void Delete(Key taskKey)
	{
		Task task = GetTask(taskKey);
		task.setDeleted(true);
		task.setTaskKey(taskKey);
		this.Update(task);
	}
	
	public Task GetTask(Key taskKey)
	{
		Entity taskEntity = super.GetEntityInfo(taskKey);
		if (taskEntity == null)
			return null;
		
		Task task = new Task();
		task.setCompleted(Boolean.parseBoolean(taskEntity.getProperty("Completed").toString()));
		task.setContent(taskEntity.getProperty("Content").toString());
		task.setTaskKey(taskKey);
		task.setUserID(taskEntity.getProperty("UserID").toString());
		task.setDeleted(Boolean.parseBoolean(taskEntity.getProperty("Deleted").toString()));
		
		return task;
	}
	
	public List<Task> GetTasks(String userID)
	{
		List<Task> tasks = new ArrayList<Task>();
		
		Query q = new Query(entityName);
		q.addFilter("UserID", Query.FilterOperator.EQUAL, userID);
		q.addFilter("Deleted", Query.FilterOperator.EQUAL, false);
		q.addFilter("Completed", Query.FilterOperator.EQUAL, false);
		
		for (Entity taskEntity : super.getResult(q))
		{
			Task task = new Task();
			
			task.setCompleted(Boolean.parseBoolean(taskEntity.getProperty("Completed").toString()));
			task.setContent(taskEntity.getProperty("Content").toString());
			task.setTaskKey(taskEntity.getKey());
			task.setUserID(taskEntity.getProperty("UserID").toString());
			task.setDeleted(Boolean.parseBoolean(taskEntity.getProperty("Deleted").toString()));
			
			tasks.add(task);
		}
		
		return tasks;
	}
}
